import subprocess
import os

def convert_video_to_h264(file_path):
    """
    将指定路径的MP4视频文件转换为H.264编码格式并替换原文件。

    参数:
    file_path (str): MP4文件的全路径。

    返回:
    str: 成功或失败的消息。
    """
    # 定义临时文件路径
    temp_file_path = file_path.replace('.mp4', '_temp.mp4')

    # 定义FFmpeg命令
    command = [
        'ffmpeg',
        '-i', file_path,
        '-vcodec', 'h264',
        temp_file_path
    ]

    # 运行命令
    try:
        subprocess.run(command, check=True)
        print("视频转换成功！")

        # 删除原文件
        os.remove(file_path)

        # 重命名临时文件为原文件名
        os.rename(temp_file_path, file_path)

        return "文件已替换！"
    except subprocess.CalledProcessError as e:
        return f"视频转换失败：{e}"
    except FileNotFoundError:
        return "FFmpeg 未安装或未添加到系统路径中。"
    except Exception as e:
        return f"发生未知错误：{e}"

# 示例调用
# file_path = r'D:\Work\PythonProjects\wyr\ultralytics-main\video\DJI_20240607163613_0001_W_out.mp4'
# result = convert_video_to_h264(file_path)
# print(result)


#
import subprocess
import json

# # 定义文件路径
# file_path = r'D:\Work\PythonProjects\wyr\ultralytics-main\output_results\test.mp4'
#
# # 定义FFprobe命令
# command = [
#     'ffprobe',
#     '-v', 'error',
#     '-select_streams', 'v:0',
#     '-show_entries', 'stream=codec_name',
#     '-of', 'json',
#     file_path
# ]

# # 运行命令并获取输出
# try:
#     result = subprocess.run(command, capture_output=True, text=True, check=True)
#     output = result.stdout
#
#     # 解析JSON输出
#     metadata = json.loads(output)
#     codec_name = metadata['streams'][0]['codec_name']
#
#     print(f"视频编码格式：{codec_name}")
# except subprocess.CalledProcessError as e:
#     print("获取视频编码格式失败：", e)
# except FileNotFoundError:
#     print("FFprobe 未安装或未添加到系统路径中。")
# except Exception as e:
#     print("发生未知错误：", e)
